//
//  ShoppingCartViewController.swift
//  BookStore2.0
//
//  Created by hw on 2022/6/1.
//

import UIKit

class ShoppingCartViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
    
    var bookId:String?
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var buyBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let xib=UINib(nibName: "ShoppingCartTableViewCell", bundle: nil)
        
        tableView.register(xib, forCellReuseIdentifier: "shoppingcartcell")
        
        tableView.rowHeight=130
        // Do any additional setup after loading the view.
    }
    //载入界面，更新数据
    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
        ShoppingCart.sharedinstance.updateBookCopiesData()
        if ShoppingCart.sharedinstance.cartContents.count==0{
            buyBtn.isEnabled=false
        }else { buyBtn.isEnabled=true}
    }
    //每次离开保存到数据库
    override func viewWillDisappear(_ animated: Bool) {
        //存到数据库中
        ShoppingCart.sharedinstance.outputBookCopy()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ShoppingCart.sharedinstance.cartContents.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shoppingcartcell", for: indexPath) as! ShoppingCartTableViewCell
        let bookcopies=ShoppingCart.sharedinstance.bookCopiesData
        if bookcopies != nil{
            let bookid=bookcopies![indexPath.row]["id"] as! String
            cell.img2.image=DB1.imgSet[bookid]
            cell.title2.text=bookcopies![indexPath.row]["title"] as? String
            let eachprice=(bookcopies![indexPath.row]["eachprice"] as! NSNumber).floatValue
            cell.eachprice2.text="\(eachprice)"
            let amount=(bookcopies![indexPath.row]["amount"] as! NSNumber).intValue
            let floatamount=Float(amount)
            cell.amount2.text="\(amount)"
            cell.totalprice2.text="\(floatamount*eachprice)"
        }
        return cell
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
       if editingStyle == .delete
        {
            DB1.deleteBookCopy(id:ShoppingCart.sharedinstance.cartContents[indexPath.row].id)
            ShoppingCart.sharedinstance.deleteBookCopy(index: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
       }
       
   }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       let bookcopies=ShoppingCart.sharedinstance.bookCopiesData
       bookId=bookcopies![indexPath.row]["id"] as? String
       performSegue(withIdentifier: "detail", sender: self)
      }    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier=="buy" {
            // Get the new view controller using segue.destination.
            let nextVC=segue.destination as! BuyingViewController
            // Pass the selected object to the new view controller.
            let cost=ShoppingCart.sharedinstance.getTotalCost()
            let num=ShoppingCart.sharedinstance.getTotalNum()
            nextVC.Price=cost
            nextVC.BookNum=num
        }else {
            let bookdetailVC=segue.destination as! BookDetailViewController
            bookdetailVC.ID=bookId
        }
    }
    @IBAction func unwindToShoppingCart(_ unwindSegue: UIStoryboardSegue) {
        // Use data from the view controller which initiated the unwind segue
        self.tableView.reloadData()
    }
}
